package com.jie.eclipse.pan.editors.utils;

import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

import com.jie.eclipse.pan.utils.StringHelper;
import com.jie.eclipse.pan.utils.Utils;

/**
 * WTP structured model助手类，提供了针对语义Document（DOM Document和CSS Document）的常用操作。
 *
 * @author zhuxing (mailto:zhu_xing@live.cn)
 */
/*
 * 修改历史
 * $Log$ 
 */
public class StructuredModelUtil {
	/**
	 * utility class
	 */
	public StructuredModelUtil() {}
	
	/**
	 * 获取特定位置对应的dom attr（目前只处理DOM模型的情况）
	 * 
	 * @param structuredModel    structured model
	 * @param offset             document offset
	 * @return                   如果当前offset不是在特定dom attr区域内，返回null
	 */
	@SuppressWarnings("restriction")
	public static  IDOMAttr getAttrAtOffset(IStructuredModel structuredModel, int offset) {
		if (!(structuredModel instanceof IDOMModel))
			return null;
		
		IndexedRegion region = structuredModel.getIndexedRegion(offset);
		if (!(region instanceof IDOMElement))
			return null;
		
		IDOMElement domElement = (IDOMElement)region;
		NamedNodeMap attributes = domElement.getAttributes();
		if (attributes == null)
			return null;
		
		//遍历属性列表，定位对应的dom attr
		for (int index = 0; index < attributes.getLength(); index++) {
			IDOMAttr attribute = (IDOMAttr)attributes.item(index);
			int len = StringHelper.getValue(attribute.getValueRegionText()).length();
			int endOffset = attribute.getValueRegionStartOffset() + (len > 0 && attribute.getValueRegion() != null ? len -1 : len );
			if(endOffset <= 0 )
				endOffset = attribute.getEndOffset();
			
			if (offset >= attribute.getStartOffset() && offset <= endOffset){
//				Utils.print("offset="+offset);
//				Utils.print("attribute.getStartOffset()="+attribute.getStartOffset());
//				Utils.print("attribute.getEndOffset()="+attribute.getEndOffset());
//				Utils.print("len2="+endOffset);
//				Utils.print("len1="+attribute.getValueRegionText()+"-");
				return attribute;
			}
		}
		
		return null;
	}
	
	@SuppressWarnings("restriction")
	public static IDOMElement getElementAtOffset(IStructuredModel structuredModel, int offset){
		if (!(structuredModel instanceof IDOMModel))
			return null;
		
		IndexedRegion region = structuredModel.getIndexedRegion(offset);
		if (!(region instanceof IDOMElement))
			return null;
		
		IDOMElement domElement = (IDOMElement)region;
		return domElement;
	}
}
